from rest_framework import serializers
from rest_framework.pagination import PageNumberPagination
from django.contrib.auth.hashers import make_password
from apps.backend import models

class PageNumberPagination(PageNumberPagination):
    page_size_query_param = 'size'
    page_size = 15
    max_page_size = 50
    def get_paginated_response(self, data):
        return {'total': self.page.paginator.count, 'list': data}
    
class RoleModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Roles    
        fields = ["id", "role_name"]
        extra_kwargs = {
            "id": {"read_only": False},
            "role_name": {"read_only": True}
        }

class AdminMoldeSerializer(serializers.ModelSerializer):
    name = serializers.CharField()
    scope = serializers.CharField()
    is_active = serializers.CharField()
    confirm_password = serializers.CharField(write_only=True)
    scope_text = serializers.CharField(source="get_scope_display", read_only=True)
    active_text = serializers.CharField(source="get_is_active_display", read_only=True)
    role = RoleModelSerializer(many=False)

    class Meta:
        model = models.SystemAdmin
        fields = ["id", "username", "password", "confirm_password", "name", "pid", "role", "scope", "is_active", "active_text", "scope_text"] 
        extra_kwargs = {
            "pid": {
                "read_only": True 
            },
            "username": {
                "max_length": 20,
                "min_length": 5
            },
            "password": {
                "max_length": 20,
                "min_length": 6, 
                "write_only": True
            }
        }

    def validate_username(self, value): 
        exists = models.SystemAdmin.objects.filter(username=value).exists()
        if exists:
            raise serializers.ValidationError('用户名已存在')
        return value
        
    def validate(self, attrs):
        if attrs['password'] != attrs['confirm_password']:
            raise serializers.ValidationError('两次输入的密码不一致')
        return attrs


    def create(self, validated_data):
        validated_data.pop('confirm_password')
        validated_data['password'] = make_password(validated_data['password'])
        role_id = validated_data.pop('role')['id']
        validated_data['role_id'] = role_id
        user_object = models.SystemAdmin.objects.create(**validated_data)
        return user_object

class AdminMoldeUpdateSerializer(serializers.ModelSerializer):
    name = serializers.CharField()
    scope = serializers.CharField()
    is_active = serializers.CharField()

    class Meta:
        model = models.SystemAdmin
        fields = ["username", "name", "scope", "is_active"] 
        extra_kwargs = {
            "username": {
                "max_length": 20,
                "min_length": 5
            }
        }
    
    def update(self, instance, validated_data):
        instance.username = validated_data.get('username', instance.username)
        instance.name = validated_data.get('name', instance.name)
        instance.scope = validated_data.get('scope', instance.scope)
        instance.is_active = validated_data.get('is_active', instance.is_active)
        instance.save()
        return instance    

